//
//  NetAPIClient.m
//  Normal
//
//  Created by 8b410-2 on 16/12/9.
//  Copyright © 2016年 abb. All rights reserved.
//


#import "OSCNetAPIClient.h"
#define kNetworkMethodName @[@"Get", @"Post"]
@implementation OSCNetAPIClient
static OSCNetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;

+ (OSCNetAPIClient *)shareJsonClient {
    dispatch_once(&onceToken,^{
        _sharedClient = [[OSCNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURLStr]];
    });
    return _sharedClient;
}

+ (id)changeJsonClient {
    _sharedClient = [[OSCNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseURLStr]];
    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    return  self;
}
#pragma 网络请求


- (RACSignal *)requestJsonDataWithPath:(NSString *)path Params:(NSDictionary *)params {
    DebugLog(@"\n=============request=============\n%@:\n%@",path,params);
    return [[[self rac_POST:path parameters:params]
            catch:^RACSignal *(NSError *error) {
                DebugLog(@"\n=============error=============\n%@:\n%@",path,error);
                return [RACSignal error:error];
            }]
     reduceEach:^id(id responseObject,NSURLResponse *response){
         DebugLog(@"\n=============response=============\n%@:\n%@",path,responseObject);
         return responseObject;
     }];
    

}
- (RACSignal *)requestUpdateWithPath:(NSString *)path
                              Params:(NSDictionary *)params
                               Datas:(NSArray<NSData *> *)datas
                            DataName:(NSString *)dataName
                            mimeType:(NSString *)mimeType {
    DebugLog(@"\n=============request=============\n%@:\n%@",path,params);
    return [[[self rac_POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [datas enumerateObjectsUsingBlock:^(NSData * _Nonnull data, NSUInteger idx, BOOL * _Nonnull stop) {
            [formData appendPartWithFileData:data name:dataName fileName:[@(idx) stringValue] mimeType:mimeType];
        }];
    }] catch:^RACSignal *(NSError *error) {
        DebugLog(@"\n=============error=============\n%@:\n%@",path,error);
        return [RACSignal error:error];
    }] reduceEach:^id(id responseObject,NSURLResponse *response){
        DebugLog(@"\n=============response=============\n%@:\n%@",path,responseObject);
        return responseObject;
    }];
}
@end
